package com.pan.interceptors;

import com.pan.controller.tools.Methods;
import com.pan.controller.tools.ThreadLocalUtil;
import com.pan.domain.ThreadLocalData;
import com.pan.domain.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class Interceptor implements HandlerInterceptor {

    Methods methods = new Methods();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取ip，uri与username
        String userIp = methods.getUserIp(request);
        String uri = request.getRequestURI();
        HttpSession session = request.getSession();
        //此处需要判断session中是否存在user，因为登录和注册时是没有对象的
        String username;
        ThreadLocalData data = new ThreadLocalData();
        if (null != session.getAttribute("user")) {
            User user = (User) session.getAttribute("user");
            username = user.getUsername();
        } else {
            username = "从前方提交的信息中获取";
        }

        //设置实体类属性
        data.setUsername(username);
        data.setUri(uri);
        data.setIp(userIp);
        //保存
        ThreadLocalUtil.addUserE(data);
        return true;
    }


    //访问结束，删除用户信息
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
